from django.http import HttpResponseNotFound
from django.shortcuts import render
from .Bilibili_Analysis import bv_predictor
from .form import BVForm

import re

bv_pattern = re.compile(r'^BV[A-Za-z0-9]{10}$')

p = bv_predictor()
p.send(None)

# BV1db4y1B7Ul


def evaluation(request):
    content = {}
    if request.method == "POST":
        form = BVForm(request.POST)
        if form.is_valid():
            global p, bv_pattern
            # 返回信息及结果
            bv = form.cleaned_data["bv"]
            if bv_pattern.match(bv) is not None:
                try:
                    result = p.send(bv)
                except StopIteration:
                    p = bv_predictor()
                    p.send(None)
                    result = p.send(bv)
                if result['aid']:
                    content["result"] = p.send(form.cleaned_data["bv"])
                    content["form"] = form
                    return render(request, "evaluation.html", content)
                else:
                    return HttpResponseNotFound("404 NotFound: 视频不存在")
            else:
                return HttpResponseNotFound("404 NotFound: BV号格式错误")
    if request.method == "GET":
        form = BVForm()
        content["form"] = form
        return render(request, "evaluation.html", content)
